package com.whut.whw.find;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.whut.whw.R;
import com.whut.whw.base.BaseFragment;
import com.whut.whw.search.SearchActivity;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.ToastUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import net.lucode.hackware.magicindicator.MagicIndicator;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.R.id.list;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/09
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class FindFragment extends BaseFragment {
    private Banner mBanner;
    private ViewPager mViewPager;

    private String[] images = {"http://img2.imgtn.bdimg.com/it/u=3093785514,1341050958&fm=21&gp=0.jpg",
            "http://img2.3lian.com/2014/f2/37/d/40.jpg",
//            "http://d.3987.com/sqmy_131219/001.jpg",
            "http://img2.3lian.com/2014/f2/37/d/39.jpg",
            "http://img2.3lian.com/2014/f2/37/d/39.jpg",
            "http://www.8kmm.com/UploadFiles/2012/8/201208140920132659.jpg",
            "http://f.hiphotos.baidu.com/image/h%3D200/sign=1478eb74d5a20cf45990f9df460b4b0c/d058ccbf6c81800a5422e5fdb43533fa838b4779.jpg",
            "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg"
    };
    private FragmentPagerAdapter mAdapter;
    private static final int[] mTitles = new int[]{R.string.find_tab1,
            R.string.find_tab2};
    private TabFragment[] mFragments = new TabFragment[mTitles.length];
    private static final String TAG = "FindFragment";
    private static MySwipeRefreshLayout mRefresh;
    private Toolbar toolbar;
    private TabLayout mTab;


    public static MySwipeRefreshLayout getmRefresh() {
        return mRefresh;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_find, null);
        toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        mRefresh = (MySwipeRefreshLayout) rootView.findViewById(R.id.srl_find_refresh);
        StickyNavLayout snl = (StickyNavLayout) rootView.findViewById(R.id.snl_find_nav);
        mRefresh.setmStickyNavLayout(snl);
        mBanner = (Banner) rootView.findViewById(R.id.banner_find_banner);
        mTab = (TabLayout) rootView.findViewById(R.id.id_stickynavlayout_indicator);
        mViewPager = (ViewPager) rootView.findViewById(R.id.id_stickynavlayout_viewpager);
        return rootView;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initToolbar();
        initRefresh();
        initBanner();
        initViewPager();
        initTabLayout();

    }

    private void initTabLayout() {
        mTab.setupWithViewPager(mViewPager);//绑定viewpager，使之可联动
        for(int i=0;i<mTitles.length;i++) {
            mTab.getTabAt(i).setText(mTitles[i]);
        }

    }

    /**
     * 初始化toolbar
     */
    private void initToolbar() {
        // 表明该Fragment愿意显示item
//        setHasOptionsMenu(true);
//        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        // 将toolbar作为独立控件使用
        toolbar.inflateMenu(R.menu.fragment_find_nav_menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.find_nav_search:
                        // 启动搜索Activity
                        Intent intent = new Intent(getContext(), SearchActivity.class);
                        startActivity(intent);
                        break;

                }
                return false;
            }
        });
    }


    /**
     * 初始化刷新控件，增加下拉刷新功能
     */
    private void initRefresh() {
        mRefresh.setColorSchemeResources(R.color.colorPrimary);
       /* mRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });*/

        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                /*new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        List<GoodsEntity> list = getData();
                        int index = mViewPager.getCurrentItem();
                        mFragments[index].refreshData(list);
                        mRefresh.setRefreshing(false);
                    }
                }, 2000);*/
                int index = mViewPager.getCurrentItem();
                mFragments[index].refreshData();
            }
        });
    }


    private void initViewPager() {
        for (int i = 0; i < mTitles.length; i++) {
            mFragments[i] = TabFragment.newInstance(getResources().getString(mTitles[i]));
        }
        mAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments[position];
            }

            @Override
            public int getCount() {
                return mTitles.length;
            }
        };
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
    }


    /**
     * 初始化轮播控件
     */
    private void initBanner() {
        LogUtils.d(TAG, mBanner == null);
        //设置图片加载器
        mBanner.setImageLoader(new GlideImageLoader())
                //设置图片集合
                .setImages(Arrays.asList(images))
                //设置自动轮播，默认为true
                .isAutoPlay(true)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setIndicatorGravity(BannerConfig.CENTER)
                // 设置是否允许手滑
                .setViewPagerIsScroll(true)
                .start();//banner设置方法全部调用完毕时最后调用
    }

    class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).into(imageView);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        // 开始轮播
        mBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        // 结束轮播
        mBanner.stopAutoPlay();
    }

    public static FindFragment newInstance() {
        return new FindFragment();
    }

    @Override
    public void setListener() {
        if (mBanner != null) {
            mBanner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    ToastUtils.showShort("你点击了：" + position);
                }
            });
        }
    }
}
